package com.chaos.eurekaproducer.juc;

import java.util.concurrent.TimeUnit;

/**
 * @author liaopeng
 * @title: InterruptDemo1
 * @projectName eureka-producer
 * @description: 非阻塞状态调用Interrupt方法
 * @date 2022/3/12下午9:17
 */
public class InterruptDemo1 extends Thread{
    @Override
    public void run() {
        while (true){
            if (Thread.currentThread().isInterrupted()) {
                System.out.println("the thread is interrupted");
            }else {
                System.out.println("the thread is running");
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        InterruptDemo1 thread = new InterruptDemo1();
        //设置线程为守护线程，不然的话会一直运行，设置为守护线程后，当main线程执行完后，JVM判断没有非守护线程了就会停止守护线程
        thread.setDaemon(true);
        thread.start();
        //main线程休眠1s，保证中断前能够运行非中断的代码
        TimeUnit.SECONDS.sleep(1);
        //中断线程，将中断状态设置为true，再执行run方法的时候就会走中断的逻辑
        thread.interrupt();
    }
}
